<template>
  <div class="question-selector">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="题目内容" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入题目关键词"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="所属章节" prop="chapterId">
        <el-tree-select
          v-model="queryParams.chapterId"
          :data="chapterOptions"
          :props="{ value: 'chapterId', label: 'chapterName', children: 'children' }"
          value-key="chapterId"
          placeholder="请选择所属章节"
          check-strictly
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="难度" prop="difficulty">
        <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable style="width: 120px">
          <el-option
            v-for="i in 5"
            :key="i"
            :label="getDifficultyLabel(i)"
            :value="i"
          >
            <el-rate
              :model-value="i"
              disabled
              show-score
              text-color="#ff9900"
              :texts="['简单', '较简单', '中等', '较难', '困难']"
            />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仅已选中">
        <el-switch
          v-model="onlyShowSelected"
          @change="handleOnlySelectedChange"
          active-text="显示已选"
          inactive-text="显示全部"
          :active-color="'#409EFF'"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="selection-info">
      已选择 {{ selectedCount }}/{{ maxSelectCount }} 题
    </div>

    <el-table
      v-loading="loading"
      :data="questionList"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="题干内容" align="center" prop="questionContent" min-width="200">
        <template #default="scope">
          <el-popover
            placement="top-start"
            trigger="hover"
            :width="400"
          >
            <div v-html="renderMathContent(scope.row.questionContent)"></div>
            <template #reference>
              <div class="content-cell" v-html="renderMathContent(formatContent(scope.row.questionContent))"></div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="所属章节" align="center" prop="chapterName" width="180">
        <template #default="scope">
          {{ getChapterName(scope.row.chapterId) }}
        </template>
      </el-table-column>
      <el-table-column label="难度" align="center" prop="difficulty" width="100">
        <template #default="scope">
          <el-rate
            v-model="scope.row.difficulty"
            disabled
            show-score
            text-color="#ff9900"
            :texts="['简单', '较简单', '中等', '较难', '困难']"
          />
        </template>
      </el-table-column>
      <el-table-column label="错误次数" align="center" prop="wrongCount" width="100">
        <template #default="scope">
          <span class="wrong-count-tag">{{ scope.row.wrongCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分值" align="center" prop="score" width="80">
        <template #default="scope">
          <span class="score-tag">{{ scope.row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handlePreview(scope.row)">预览</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handlePageChange"
    />

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="题目预览"
      width="600px"
      append-to-body
      @opened="renderMathInPreview" 
    >
      <div class="preview-container" ref="previewContainer">
        <!-- 题目类型 -->
        <div class="preview-type">
          <el-tag :type="getQuestionTypeTag(previewQuestion.questionType)">
            {{ getQuestionTypeLabel(previewQuestion.questionType) }}
          </el-tag>
          <span class="preview-difficulty">
            <el-rate
              v-model="previewQuestion.difficulty"
              disabled
              show-score
              text-color="#ff9900"
              :texts="['简单', '较简单', '中等', '较难', '困难']"
            />
          </span>
          <span class="preview-score">分值: {{ previewQuestion.score }}</span>
          <span class="preview-wrong-count">错误次数: {{ previewQuestion.wrongCount }}</span>
        </div>

        <!-- 题干 -->
        <div class="preview-title">题干:</div>
        <div class="preview-content content-html" v-html="previewQuestion.questionContent"></div>
        
        <!-- 选项 - 单选题/多选题 -->
        <template v-if="previewQuestion.questionType === 0 || previewQuestion.questionType === 1">
          <div class="preview-title">选项:</div>
          <div v-for="option in previewQuestion.options" :key="option.optionId" class="preview-option">
            <span class="option-label">{{ option.optionLabel }}.</span>
            <div class="preview-option-content content-html" v-html="option.optionContent"></div>
          </div>
        </template>

        <!-- 答案 -->
        <div class="preview-title">答案:</div>
        <!-- 单选题/多选题答案 -->
        <div v-if="previewQuestion.questionType === 0 || previewQuestion.questionType === 1" class="preview-answer">
          {{ previewQuestion.answer }}
        </div>
        <!-- 判断题答案 -->
        <div v-else-if="previewQuestion.questionType === 2" class="preview-answer">
          {{ formatJudgeAnswer(previewQuestion.answer) }}
        </div>
        <!-- 填空题答案 -->
        <div v-else-if="previewQuestion.questionType === 3">
          <div v-for="(option, index) in previewQuestion.options" :key="index" class="preview-blank">
            <div class="preview-blank-label">填空 {{ option.optionLabel }}:</div>
            <div class="preview-blank-answers">
              {{ option.optionContent?.split('|||').join(' 或 ') || '' }}
            </div>
          </div>
        </div>
        <!-- 简答题答案 -->
        <div v-else-if="previewQuestion.questionType === 4" class="preview-answer" v-html="previewQuestion.answer"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { getQuestion } from '@/api/manage/question';
import { listChapter } from '@/api/manage/chapter';
import { listWrongQuestions, listStudentWrongQuestions } from '@/api/manage/wrongQuestion';
import useUserStore from '@/store/modules/user';
import katex from 'katex';
import 'katex/dist/katex.min.css';
import pagination from '@/components/Pagination';

const props = defineProps({
  questionType: {
    type: Number,
    required: true
  },
  maxSelectCount: {
    type: Number,
    required: true
  },
  selectedQuestions: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:selectedQuestions']);
const userStore = useUserStore();

// 数据列表
const questionList = ref([]);
const total = ref(0);
const loading = ref(false);
const tableRef = ref(null);
const chapterOptions = ref([]);
const isInitialSetup = ref(true); // 用于防止初始化时的循环触发
const onlyShowSelected = ref(false); // 是否只显示已选中题目
const isPageChanging = ref(false); // 是否正在进行页面切换操作

// 预览相关
const previewVisible = ref(false);
const previewQuestion = ref({});
const previewContainer = ref(null);

// 已选择的计数
const selectedCount = computed(() => props.selectedQuestions.length);

// 用于缓存章节名称的映射
const chapterNameMap = ref({});

// 题目类型选项
const questionTypeOptions = [
  { value: 0, label: '单选题' },
  { value: 1, label: '多选题' },
  { value: 2, label: '判断题' },
  { value: 3, label: '填空题' },
  { value: 4, label: '简答题' }
];

// 查询条件
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  questionType: props.questionType,
  chapterId: null,
  difficulty: null,
  keyword: '',
  studentNumber: userStore.name === 'admin' ? '1000000001' : useUserStore().name
});

// 获取难度标签
const getDifficultyLabel = (level) => {
  const labels = ['简单', '较简单', '中等', '较难', '困难'];
  return labels[level - 1] || '';
};

/** 获取题目类型标签 */
const getQuestionTypeLabel = (type) => {
  const option = questionTypeOptions.find(opt => opt.value === type);
  return option ? option.label : '';
};

/** 获取题目类型标签样式 */
const getQuestionTypeTag = (type) => {
  const types = ['success', 'warning', 'info', 'danger', 'primary'];
  return types[type] || 'default';
};

/** 获取章节名称 */
const getChapterName = (chapterId) => {
  if (!chapterId) return '';
  
  // 如果已经缓存了章节名称，直接返回
  if (chapterNameMap.value[chapterId]) {
    return chapterNameMap.value[chapterId];
  }
  
  const path = [];
  const findPath = (chapters, id) => {
    for (const chapter of chapters) {
      if (chapter.chapterId === id) {
        path.unshift(chapter.chapterName);
        return true;
      }
      if (chapter.children) {
        if (findPath(chapter.children, id)) {
          path.unshift(chapter.chapterName);
          return true;
        }
      }
    }
    return false;
  };
  
  findPath(chapterOptions.value, chapterId);
  const fullPath = path.join(' / ');
  
  // 缓存结果
  chapterNameMap.value[chapterId] = fullPath;
  
  return fullPath;
};

// 设置表格选中状态
const setTableSelection = () => {
  if (!tableRef.value) {
    console.error('表格引用不存在，无法设置选中状态');
    return;
  }
  
  // 在设置选中状态前，先锁定选择变更处理
  isPageChanging.value = true;
  
  console.log('开始设置表格选中状态，页码:', queryParams.pageNum);
  
  // 清空当前选择
  tableRef.value.clearSelection();
  
  // 获取所有已选题目的ID，用于快速查找
  const selectedIds = props.selectedQuestions.map(item => item.questionId);
  console.log('设置表格选中状态，当前页面题目数:', questionList.value.length, '已选题目数:', selectedIds.length);
  
  // 使用nextTick确保DOM已更新
  nextTick(() => {
    try {
      // 遍历当前页面上的题目，将已选中的题目设置为选中状态
      questionList.value.forEach(row => {
        if (selectedIds.includes(row.questionId)) {
          // 使用nextTick确保选中状态正确应用
          nextTick(() => {
            tableRef.value.toggleRowSelection(row, true);
          });
        }
      });
    } catch (err) {
      console.error('设置选中状态时发生错误:', err);
    }
    
    // 延迟解除锁定，确保UI已完全更新
    setTimeout(() => {
      isPageChanging.value = false;
      console.log('表格选中状态设置完成，解除锁定');
    }, 200);
  });
};

// 添加数学公式渲染函数
const renderMathContent = (content) => {
  if (!content) return '';
  
  try {
    // 处理块级公式 $$...$$
    content = content.replace(/\$\$([\s\S]+?)\$\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          displayMode: true,
          throwOnError: false
        });
      } catch (err) {
        console.error('KaTeX error:', err);
        return match;
      }
    });

    // 处理行内公式 $...$
    content = content.replace(/\$([^\$]+)\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          displayMode: false,
          throwOnError: false
        });
      } catch (err) {
        console.error('KaTeX error:', err);
        return match;
      }
    });

    return content;
  } catch (err) {
    console.error('Content processing error:', err);
    return content;
  }
};

/** 格式化内容 - 新版本支持同时显示文本和图片 */
const formatContent = (content) => {
  if (!content) return '';
  
  // 创建临时DOM元素解析内容
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = content;
  
  // 查找图片元素
  const images = tempDiv.querySelectorAll('img');
  let hasImage = images.length > 0;
  
  // 获取纯文本内容（用于显示文字部分）
  let textContent = tempDiv.textContent || '';
  textContent = textContent.trim();
  
  // 截断文本，保留前30个字符
  let truncatedText = textContent.length > 30 ? textContent.substring(0, 30) + '...' : textContent;
  
  // 如果有图片，创建带图片的预览
  if (hasImage) {
    // 只保留第一张图片作为缩略图
    const firstImage = images[0];
    
    // 设置图片缩略图样式
    firstImage.style.maxWidth = '100%';
    firstImage.style.maxHeight = '40px';
    firstImage.style.objectFit = 'contain';
    firstImage.style.display = 'block';
    firstImage.style.margin = '5px auto';
    
    // 返回文本+图片组合或仅图片（如果没有文字）
    if (truncatedText) {
      return `<div>${truncatedText}</div><div class="thumbnail-preview">${firstImage.outerHTML}</div>`;
    } else {
      return `<div class="thumbnail-preview">${firstImage.outerHTML}</div>`;
    }
  }
  
  // 没有图片，只返回文本
  return truncatedText;
};

/** 获取错题列表 */
const getList = () => {
  if (!queryParams) return;
  
  // 开启页面切换锁定
  isPageChanging.value = true;
  console.log('开始获取错题列表，启用页面切换锁定');
  loading.value = true;
  
  // 获取当前用户的学号
  queryParams.studentNumber = useUserStore().name;
  
  // 当前页已选择的题目ID
  const selectedIds = props.selectedQuestions.map(q => q.questionId);
  
  // 加载数据的方法
  const loadData = () => {
    // 根据筛选条件，判断是获取已选择的题目，还是获取所有题目
    if (onlyShowSelected.value && selectedIds.length > 0) {
      // 只显示已选择的题目
      console.log('仅显示已选择的', selectedIds.length, '题');
      // 将ID数组转成逗号分隔的字符串
      const idsStr = selectedIds.join(',');
      // 请求后台获取详情（实际上全部ID都发给后台，由前端在页面上分页显示）
      getQuestion(idsStr).then(response => {
        // 将后台返回的数据设置到表格
        questionList.value = response.data || [];
        total.value = questionList.value.length;
        
        // 设置选中状态
        nextTick(() => {
          setTableSelection();
          isInitialSetup.value = false;
          // 完成数据加载后，解除页面切换状态
          setTimeout(() => {
            isPageChanging.value = false;
            console.log('页面加载完成，解除切换锁定');
          }, 200);
        });
        loading.value = false;
      }).catch(error => {
        console.error('获取错题列表失败:', error);
        loading.value = false;
        isPageChanging.value = false;
        ElMessage.error('获取错题列表失败');
      });
    } else if (onlyShowSelected.value && selectedIds.length === 0) {
      // 如果没有选中的题目但开启了"只显示已选中"，显示空列表
      questionList.value = [];
      total.value = 0;
      loading.value = false;
      isInitialSetup.value = false;
      isPageChanging.value = false;
    } else {
      // 正常模式：显示学生个人错题
      listStudentWrongQuestions({
        ...queryParams,
        questionType: props.questionType
      }).then(response => {
        questionList.value = response.rows;
        total.value = response.total;
        
        // 设置选中状态
        nextTick(() => {
          setTableSelection();
          isInitialSetup.value = false;
          // 完成数据加载后，解除页面切换状态
          setTimeout(() => {
            isPageChanging.value = false;
            console.log('页面加载完成，解除切换锁定');
          }, 200);
        });
        loading.value = false;
      }).catch(error => {
        console.error('获取个人错题列表失败:', error);
        loading.value = false;
        isPageChanging.value = false;
        ElMessage.error('获取个人错题列表失败');
      });
    }
  };
  
  // 执行数据加载
  loadData();
};

/** 获取章节树形数据 */
const getChapterTreeselect = () => {
  listChapter().then(response => {
    const data = { chapterId: 0, chapterName: '离散数学', children: [] };
    data.children = handleTree(response.data, "chapterId", "parentId");
    chapterOptions.value = [data];
    
    // 获取章节数据后重新获取题目列表
    getList();
  }).catch(error => {
    console.error('获取章节数据失败:', error);
    ElMessage.error('获取章节数据失败');
    
    // 即使章节获取失败也要显示题目列表
    getList();
  });
};

// 添加处理树形结构的方法
const handleTree = (data, id, parentId) => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (const d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (const d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
};

/** 查询按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.keyword = '';
  queryParams.chapterId = null;
  queryParams.difficulty = null;
  queryParams.pageNum = 1;
  onlyShowSelected.value = false; // 重置"仅显示已选中"开关
  
  // 开启页面切换锁定
  isPageChanging.value = true;
  
  getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  // 防止初始化时的重复触发
  if (isInitialSetup.value) {
    console.log('初始化中，忽略选择变更事件');
    return;
  }
  
  // 防止页面切换时的误触发
  if (isPageChanging.value) {
    console.log('页面切换中，忽略选择变更事件');
    return;
  }
  
  console.log('处理选择变更，当前选中数:', selection.length);
  
  // 获取当前页面上题目的ID
  const currentPageIds = questionList.value.map(q => q.questionId);
  console.log('当前页面题目IDs:', currentPageIds);
  
  // 找出当前页面上的题目与已选择题目的交集
  const currentPageSelectedIds = props.selectedQuestions
    .filter(q => currentPageIds.includes(q.questionId))
    .map(q => q.questionId);
  console.log('当前页面已选择IDs:', currentPageSelectedIds);
  
  // 找出不在当前页面的已选择题目
  const otherPageSelected = props.selectedQuestions
    .filter(q => !currentPageIds.includes(q.questionId));
  console.log('其他页面已选择题目数:', otherPageSelected.length);
  
  // 计算当前页面新选中的题目ID
  const currentSelectionIds = selection.map(q => q.questionId);
  console.log('当前选择IDs:', currentSelectionIds);
  
  // 计算当前页面取消选中的题目ID
  const unselectedIds = currentPageSelectedIds.filter(id => !currentSelectionIds.includes(id));
  console.log('取消选择的IDs:', unselectedIds);
  
  // 保存其他页面的选择 + 当前页面的选择
  let updatedSelection = [
    ...otherPageSelected,
    ...selection.map(item => ({
      ...item,
      questionType: props.questionType // 确保题型信息正确
    }))
  ];
  
  // 检查是否超过最大选择数量
  if (updatedSelection.length > props.maxSelectCount) {
    ElMessage.warning(`最多只能选择${props.maxSelectCount}道题目`);
    
    // 取消最新选中的项目
    const excessCount = updatedSelection.length - props.maxSelectCount;
    console.log(`超出最大选择数量，需要取消${excessCount}个选择`);
    
    // 重置表格选择状态
    nextTick(() => {
      // 清空表格选择
      tableRef.value.clearSelection();
      
      // 只保留最大允许数量的选择
      updatedSelection = updatedSelection.slice(0, props.maxSelectCount);
      
      // 更新已选题目
      emit('update:selectedQuestions', updatedSelection);
      
      // 重新设置表格选中状态
      nextTick(() => {
        const remainingIds = updatedSelection.map(q => q.questionId);
        questionList.value.forEach(row => {
          if (remainingIds.includes(row.questionId)) {
            tableRef.value.toggleRowSelection(row, true);
          }
        });
      });
    });
    
    return;
  }
  
  // 更新选择
  console.log('更新选择，总数:', updatedSelection.length);
  emit('update:selectedQuestions', updatedSelection);
};

/** 预览按钮操作 */
const handlePreview = (row) => {
  loading.value = true;
  // 直接从后端获取完整的题目数据，确保有选项
  getQuestion(row.questionId).then(response => {
    loading.value = false;
    // 处理获取到的数据
    let questionData = response.data;
    
    // 保留错误次数
    questionData.wrongCount = row.wrongCount;
    
    // 如果是填空题，要确保选项数据正确排序
    if (questionData.questionType === 3 && questionData.options) {
      questionData.options = questionData.options.sort((a, b) => 
        a.optionLabel.localeCompare(b.optionLabel)
      );
    }
    
    // 确保选项排序正确 (单选题和多选题)
    if ((questionData.questionType === 0 || questionData.questionType === 1) && questionData.options) {
      questionData.options = questionData.options.sort((a, b) => 
        a.optionLabel.localeCompare(b.optionLabel)
      );
    }
    
    // 更新预览数据并显示对话框
    previewQuestion.value = questionData;
    previewVisible.value = true;
  }).catch(error => {
    loading.value = false;
    console.error('获取题目详情失败', error);
    ElMessage.error('获取题目详情失败');
  });
};

/** 修改MathJax加载方式 */
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      // 如果已经加载，重新配置并尝试渲染
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
    // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
    };
    document.head.appendChild(script);
  });
};

/** 优化渲染函数，添加更多日志和重试机制 */
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    
    // 备选方案：使用KaTeX
    try {
      if (previewContainer.value) {
        // 找到所有包含数学公式的元素
        const elements = previewContainer.value.querySelectorAll('.content-html, .preview-option-content, .preview-blank-answers');
        elements.forEach(el => {
          const html = el.innerHTML;
          if (html && (html.includes('$') || html.includes('\\('))) {
            // 重新渲染数学公式
            el.innerHTML = renderMathContent(html);
          }
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

// 格式化判断题答案
const formatJudgeAnswer = (answer) => {
  const mapping = {
    'A': '正确',
    'B': '错误'
  };
  return mapping[answer] || answer;
};

// 初始化获取数据
onMounted(() => {
  getChapterTreeselect();
});

// 监听选中题目变化
watch(() => props.selectedQuestions, (newVal, oldVal) => {
  console.log('selectedQuestions 发生变化，新数量:', newVal.length);
  
  // 如果当前不在页面切换中，且有可用的表格引用，则更新表格选中状态
  if (!isPageChanging.value && tableRef.value && questionList.value.length > 0) {
    // 等待其他操作完成后再设置选中状态
    setTimeout(() => {
      isPageChanging.value = true; // 临时锁定
      setTableSelection();
    }, 100);
  }
}, { deep: true });

// 暴露给父组件的方法
defineExpose({
  refreshList: getList
});

// 新增方法：处理仅已选中题目的开关
const handleOnlySelectedChange = () => {
  console.log('切换仅显示已选中题目:', onlyShowSelected.value);
  
  // 开启页面切换锁定
  isPageChanging.value = true;
  
  // 重置页码并重新加载数据
  queryParams.pageNum = 1;
  getList();
};

// 处理分页变化
const handlePageChange = () => {
  console.log('分页变化，新页码:', queryParams.pageNum, '每页数量:', queryParams.pageSize);
  // 设置页面切换状态，防止选择变更事件被错误处理
  isPageChanging.value = true;
  getList();
};
</script>

<style scoped>
.question-selector {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 250px); /* 增加整体高度 */
  min-height: 500px; /* 确保最小高度 */
}

.selection-info {
  margin: 10px 0;
  font-size: 14px;
  color: #409EFF;
  font-weight: bold;
}

.content-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.score-tag {
  color: #E6A23C;
  font-weight: bold;
}

.wrong-count-tag {
  background-color: #FEF0F0;
  color: #F56C6C;
  border-radius: 4px;
  padding: 2px 8px;
  font-weight: bold;
}

/* 添加过渡效果 */
.answer-cell, .blank-answer-item span {
  transition: filter 0.3s ease;
}

/* 缩略图样式 */
.thumbnail-preview {
  margin-top: 5px;
}

.preview-container {
  padding: 15px;
  max-height: 60vh;
  overflow-y: auto;
}

.preview-type {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.preview-difficulty {
  margin-left: auto;
  margin-top: 4px; /* 微调垂直偏移 */
}

.preview-score {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-weight: bold;
  font-size: 12px;
  padding: 3px 8px;
}

.preview-wrong-count {
  background-color: #FEF0F0;
  border: 1px solid #F56C6C;
  border-radius: 4px;
  color: #F56C6C;
  font-weight: bold;
  font-size: 12px;
  padding: 3px 8px;
  margin-left: 10px;
}

.preview-title {
  font-weight: bold;
  margin-top: 15px;
  margin-bottom: 5px;
}

.preview-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.preview-option {
  display: flex;
  margin: 10px 0;
}

.option-label {
  width: 30px;
  text-align: center;
  font-weight: bold;
}

.preview-option-content {
  margin-left: 10px;
  flex: 1;
}

.preview-answer {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  font-weight: bold;
  color: #67c23a;
  margin-bottom: 15px;
}

.preview-blank {
  margin: 10px 0;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.preview-blank-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.preview-blank-answers {
  color: #67c23a;
  font-weight: bold;
  padding-left: 20px;
}

/* 增加表格区域弹性高度 */
:deep(.el-table) {
  flex: 1;
  margin-bottom: 10px;
}

/* 确保分页区域显示完整 */
:deep(.pagination-container) {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>